﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Supermarket;

namespace XLSupermarket.MainInterface.SuperAdmin
{
    public partial class SuperAdminForm : Form
    {
        public SuperAdminForm()
        {
            InitializeComponent();
        }
        public int EP_ID = 0;//保存上次操作的用户编号
        public bool Admin = true;
        string YCard = "";
        string YPhone = "";
        
        /// <summary>
        /// treeVeiw数据更新
        /// </summary>
        private void F_5() {
            treeView1.Nodes.Clear();//清空节点
            TreeNode admin = new TreeNode("湘龙超市");
            treeView1.Nodes.Add(admin);
            admin.Tag = 0;
            string sql = "SELECT * FROM EP_information";
            DataTable dt = new DataTable();
            dt = DBHelper.FillData(sql);
            string[] list_bool = new string[dt.Rows.Count + 1];
            foreach (DataRow item in dt.Rows)
            {
                if (Admin)
                {
                    if (item["Staff_Name"].ToString() == "财务" || item["Staff_Name"].ToString() == "店长")
                    {
                        continue;
                    }
                }
                TreeNode root = new TreeNode(item["Staff_Name"].ToString());
                TreeNode troot = new TreeNode(item["EP_Name"].ToString());
                bool pd = true;
                foreach (TreeNode items in admin.Nodes)
                {
                    if (root.Text == items.Text)
                    {
                        items.Nodes.Add(troot);
                        troot.Tag = int.Parse(item["EP_ID"].ToString());
                        pd = false;
                        break;
                    }
                }
                if (pd)
                {
                    admin.Nodes.Add(root);
                    root.Nodes.Add(troot);
                    troot.Tag = int.Parse(item["EP_ID"].ToString());
                }
            }
            admin.Expand();
            button3.Enabled = false;
        }
        /// <summary>
        /// 店长判断
        /// </summary>
        /// <returns></returns>
        private void Rank()
        {
            String sql = "select * from EP_information EI , EP_Number EN where EI.EP_ID=EN.EP_ID and Staff_Name='店长' and EN.UserName='" + LoginForm.UserName_Value + "'";
            if (DBHelper.FillData(sql).Rows.Count > 0) Admin=false;
            else Admin=true;
        }
        /// <summary>
        /// 左边TreeView显示内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SuperAdminForm_Load(object sender, EventArgs e)
        {
            Rank();
            F_5();
            button1.Enabled = true;
            button3.Enabled = false;
        }
        /// <summary>
        /// panel数据更新
        /// </summary>
        private void UpInfoMation() {
            String sql = "select * from EP_information EI LEFT JOIN EP_Number EN on(EI.EP_ID=EN.EP_ID) where EI.EP_ID='" + EP_ID + "'";
            DataTable dt = new DataTable();
            dt = DBHelper.FillData(sql);
            LB_Id.Text = dt.Rows[0]["EP_ID"].ToString();
            TX_Name.Text = dt.Rows[0]["EP_Name"].ToString();
            if (dt.Rows[0]["EP_Gender"].ToString() == "男") RB_Man.Checked = true;
            else RB_Woman.Checked = true;
            TB_Age.Text = dt.Rows[0]["EP_Age"].ToString();
            DateTime dtime = DateTime.Parse(dt.Rows[0]["EP_Birthday"].ToString());
            DT_Br.Value = dtime;
            TB_Card.Text = dt.Rows[0]["EP_IDcard"].ToString();
            YCard = TB_Card.Text;
            CB_ST.Text = dt.Rows[0]["Staff_Name"].ToString();
            TB_Phone.Text = dt.Rows[0]["EP_Phone"].ToString();
            YPhone = TB_Phone.Text;
            TX_User.Text = dt.Rows[0]["UserName"].ToString();
            TB_Pwd.Text = dt.Rows[0]["Password"].ToString();
            TB_Src.Text = dt.Rows[0]["Src"].ToString();
            TB_Addres.Text = dt.Rows[0]["EP_Address"].ToString();
            TB_Other.Text = dt.Rows[0]["Other"].ToString();
        }
        /// <summary>
        /// panel数据清空
        /// </summary>
        private void Clear() {
            LB_Id.Text = "";
            TX_Name.Text = "";
            RB_Man.Checked = true;
            TB_Age.Text = "";
            DT_Br.Value = DateTime.Now;
            TB_Card.Text = "";
            CB_ST.Text = "";
            TB_Phone.Text = "";
            TX_User.Text = "";
            TB_Pwd.Text = "";
            TB_Src.Text = "";
            TB_Addres.Text = "";
            TB_Other.Text = "";
        }
        /// <summary>
        /// 选择treeView数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                TreeNode tr = e.Node;
                string num = tr.Tag.ToString();
                EP_ID = int.Parse(num);
                if (num == "0")
                {
                    return;
                }
                UpInfoMation();
                button1.Enabled = true;
                button3.Enabled = false;
            }
            catch (Exception ex)
            {
                //抛出异常跳过
            }
        }
        /// <summary>
        /// 修改员工信息按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (InformationVerification()) return;
                if (NULLRepeated()) return;
                string gender = "男";
                if (RB_Woman.Checked) gender = "女";
                string sql_up_1 = string.Format("UPDATE EP_information SET EP_Name='{0}',EP_Gender='{1}',EP_Age='{2}',EP_IDcard='{3}',EP_Birthday='{4}',Staff_Name='{5}',EP_Phone='{6}',EP_Address='{7}',Other='{8}' where EP_ID='{9}'",
                                          TX_Name.Text, gender, TB_Age.Text, TB_Card.Text, DT_Br.Value, CB_ST.Text, TB_Phone.Text,
                                          TB_Addres.Text, TB_Other.Text, LB_Id.Text);
                string sql_up_2 = string.Format("UPDATE EP_Number SET UserName = '{0}', Password = '{1}',Src='{2}' where EP_ID = '{3}'",
                                                   TX_User.Text, TB_Pwd.Text, TB_Src.Text, LB_Id.Text);
                bool result_1 = DBHelper.Edit(sql_up_1) > 0 ? true : false;
                bool result_2 = DBHelper.Edit(sql_up_2) > 0 ? true : false;
                if (result_1) MessageBox.Show("个人信息修改成功！");
                else MessageBox.Show("个人信息修改失败！");
                if (result_2) MessageBox.Show("账户密码修改成功！");
                else MessageBox.Show("账户密码修改失败！");
                UpInfoMation();
                F_5();
            }
            catch (Exception ex) {
                MessageBox.Show("您的信息输入错误！");
            }
        }
        /// <summary>
        /// 右键新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 新增ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clear();
            button1.Enabled = false;
            button3.Enabled = true;
        }
        /// <summary>
        /// 新增员工按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                string gender = "男";
                if (RB_Woman.Checked) gender = "女";
                string datet = DT_Br.Value.ToString("yyyy-MM-dd");
                if (InformationVerification()) return;
                if (NULLRepeated()) return;
                string sql_1 = string.Format("insert into EP_information values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')",
                TX_Name.Text, gender, TB_Age.Text, TB_Card.Text, datet, CB_ST.Text, TB_Phone.Text, TB_Addres.Text, TB_Other.Text);
                string sql_2 = string.Format("INSERT into EP_Number VALUES ('{0}', '{1}', '..\\..\\Image\\Img\\{2}')",
                    TX_User.Text, TB_Pwd.Text, TB_Src.Text);
                bool result_1 = DBHelper.Edit(sql_1) > 0 ? true : false;
                bool result_2 = DBHelper.Edit(sql_2) > 0 ? true : false;
                if (result_1) MessageBox.Show("员工入职成功！");
                else MessageBox.Show("员工入职失败！");
                if (result_2) MessageBox.Show("员工账号添加成功！");
                else MessageBox.Show("员工账号添加失败！");
                string sql_3 = "select EP_ID from EP_information";
                int resu = int.Parse(DBHelper.Scal(sql_3).ToString());
                EP_ID = resu;
                UpInfoMation();
                F_5();
            }
            catch (Exception ex) {
                MessageBox.Show("信息输入有误，请检查！");
            }
        }
        /// <summary>
        /// 年龄计算
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DT_Br_ValueChanged(object sender, EventArgs e)
        {
            DateTime date_now = DateTime.Now;
            int age = date_now.Year - DT_Br.Value.Year;
            if (date_now.Month < DT_Br.Value.Month)
            {
                age--;
            }
            else if (date_now.Month == DT_Br.Value.Month && date_now.Day < DT_Br.Value.Day)
            {
                age--;
            }
            TB_Age.Text = age + "";
        }
        /// <summary>
        /// 身份证验证
        /// </summary>
        /// <param name="idCardNumber"></param>
        /// <returns></returns>
        private bool CheckChinaIDCardNumberFormat(string idCardNumber)
        {
            string idNumber = idCardNumber;
            bool result = true;
            try
            {
                if (idNumber.Length != 18)
                {
                    return false;
                }
                long n = 0;
                if (long.TryParse(idNumber.Remove(17), out n) == false
                    || n < Math.Pow(10, 16) || long.TryParse(idNumber.Replace('x', '0').Replace('X', '0'), out n) == false)
                {
                    return false;//数字验证  
                }
                string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
                if (address.IndexOf(idNumber.Remove(2)) == -1)
                {
                    return false;//省份验证  
                }
                string birth = idNumber.Substring(6, 8).Insert(6, "-").Insert(4, "-");
                DateTime time = new DateTime();
                if (DateTime.TryParse(birth, out time) == false)
                {
                    return false;//生日验证  
                }
                string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
                string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
                char[] Ai = idNumber.Remove(17).ToCharArray();
                int sum = 0;
                for (int i = 0; i < 17; i++)
                {
                    sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
                }
                int y = -1;
                Math.DivRem(sum, 11, out y);
                if (arrVarifyCode[y] != idNumber.Substring(17, 1).ToLower())
                {
                    return false;//校验码验证  
                }
                return true;//符合GB11643-1999标准 
            }
            catch (Exception ex)
            {
                //logger.Error("CheckChinaIDCardNumber 身份证校验失败  号码:" + idNumber, ex);
                result = false;
            }
            return result;
        }
        /// <summary>
        /// 信息验证
        /// </summary>
        /// <returns></returns>
        private bool InformationVerification() {
            string datet = DT_Br.Value.ToString("yyyy-MM-dd");
            if (int.Parse(TB_Age.Text) < 18)
            {
                MessageBox.Show("本超市不可入职未成年员工！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return true;
            }
            if (TB_Card.Text.Length != 18)
            {
                MessageBox.Show("身份证号码输入有误！\n请检查！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }
            if (!CheckChinaIDCardNumberFormat(TB_Card.Text))
            {
                MessageBox.Show("身份证号码输入有误！\n请检查！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }
            if (CardRepeatedJudgment())
            {
                MessageBox.Show("您的身份证已经存在！");
                return true;
            }
            if (TB_Phone.Text.Length != 11)
            {
                DialogResult result_3 = MessageBox.Show("手机号码输入非常规输入！\n号码:" + TB_Phone.Text + " 是否正确？", "提示"
                      , MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result_3 == DialogResult.No)
                {
                    MessageBox.Show("请输入正确的手机号！");
                    return true;
                }
            }
            if (PhoneRepeatedJudgment())
            {
                MessageBox.Show("您的电话号码已存在！");
                return true;
            }
            if (Admin&&(CB_ST.Text=="店长"||CB_ST.Text=="财务"))
            {
                MessageBox.Show("您不可入职店长和财务！");
                return true;
            }
            try
            {
                long a = long.Parse(TB_Phone.Text);
            }
            catch (Exception ex) {
                MessageBox.Show("您的手机号码输入有误！");
                return true; }
            return false;
        }
        /// <summary>
        /// 手机号重复验证
        /// </summary>
        /// <returns></returns>
        private bool PhoneRepeatedJudgment() {
            if (YPhone==TB_Phone.Text)
            {
                return false;
            }
            string sql = "Select EP_Phone from EP_information ";
            DataTable dt = DBHelper.FillData(sql);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i][0].ToString() == TB_Phone.Text)
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 身份证重复验证
        /// </summary>
        /// <returns></returns>
        private bool CardRepeatedJudgment()
        {
            if (YCard==TB_Card.Text)
            {
                return false;
            }
            string sql = "Select EP_IDcard from EP_information ";
            DataTable dt = DBHelper.FillData(sql);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i][0].ToString() == TB_Card.Text)
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 为空验证
        /// </summary>
        /// <returns></returns>
        private bool NULLRepeated() {
            if (TX_Name.Text=="" || TX_Name.Text.Equals(""))
            {
                MessageBox.Show("请填写姓名信息！");
                return true;
            }
            if (TB_Age.Text == "" || TB_Age.Text.Equals(""))
            {
                MessageBox.Show("请填写年龄信息！");
                return true;
            }
            if (TB_Card.Text == "" || TB_Card.Text.Equals(""))
            {
                MessageBox.Show("请填写身份证信息！");
                return true;
            }
            if (CB_ST.Text == "" || CB_ST.Text.Equals(""))
            {
                MessageBox.Show("请填写职位信息！");
                return true;
            }
            if (TB_Phone.Text == "" || TB_Phone.Text.Equals(""))
            {
                MessageBox.Show("请填写手机信息！");
                return true;
            }
            if (TX_User.Text == "" || TX_User.Text.Equals(""))
            {
                MessageBox.Show("请填写用户名信息！");
                return true;
            }
            if (TB_Pwd.Text == "" || TB_Pwd.Text.Equals(""))
            {
                MessageBox.Show("请填写密码信息！");
                return true;
            }
            if (TB_Src.Text == "" || TB_Src.Text.Equals(""))
            {
                MessageBox.Show("请填写照片信息！");
                return true;
            }
            if (TB_Addres.Text == "" || TB_Addres.Text.Equals(""))
            {
                MessageBox.Show("请填写地址信息！");
                return true;
            }
            return false;
        }
    }
}
